package com.itheima.tanhua.dubbo.mongo.api.impl;

import com.itheima.tanhua.api.VisitorsApi;
import com.itheima.tanhua.mongo.Visitors;
import com.itheima.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author Lff
 * @date 2022/4/2
 * 用户来访
 */
@DubboService
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongo;

    /**
     * 保存用户的来访记录
     *
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        Criteria c = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());
        if (!mongo.exists(Query.query(c), Visitors.class)) {
            //不存在  进行添加
            mongo.save(visitors);
        }
    }


    /**
     * 查询所有访客的记录
     *
     * @param id
     * @param date
     * @return
     */
    @Override
    public List<Visitors> findMyVisitors(Long id, Long date) {
        Criteria c = Criteria.where("userId").is(id);
        if (date != null) {
            //大于等于这个时间
            c.and("date").gte(date);
        }
        Query q = Query.query(c).with(Sort.by(Sort.Order.desc("date")))
                .limit(5);

        List<Visitors> visitors = mongo.find(q, Visitors.class);
        return visitors;
    }

    /**
     * @param userId   当前登录用户id
     * @param page     页码
     * @param pagesize 页码尺寸
     * @return
     */
    @Override
    public PageResult findVisitorPage(Long userId, Long date, Integer page, Integer pagesize) {
        Criteria c = Criteria.where("userId").is(userId);
        if (date != null) {
            //大于等于这个时间
            c.and("date").gte(date);
        }
        Query q = Query.query(c).with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Visitors> visitors = mongo.find(q, Visitors.class);
        return new PageResult(page, pagesize, Long.valueOf(visitors.size()), visitors);
    }
}
